//
//  JCArrayExtension.swift
//  JCPublicKit
//
//  Created by JasonLee on 2020/5/13.
//

import Foundation

extension Array {

    var jc_toString: String {
        var tempString = ""
        for value in self {
            tempString.append("\(value)")
        }
        return tempString
    }

    func jc_index(of closure: (_ element: Element) -> Bool) -> Int? {
        guard self.count > 0 else { return nil }
        for (index, any) in self.enumerated() {
            if closure(any) {
                return index
            }
        }
        return nil
    }
    mutating func jc_remove<T>(_ element: T) where T: Equatable {
        self = self.filter { $0 as? T != element }
    }

    @discardableResult
    mutating func jc_pop() -> Element? {
        if let first = self.first {
            self.remove(at: 0)
            return first
        }
        return nil
    }
    
}

extension Array {
    func jc_subarray(from start: Int, to end: Int) -> [Element] {
        guard !isEmpty else { return Array() }
        if start > endIndex {
            return Array()
        } else if end > endIndex {
            return Array(self[start...endIndex])
        } else {
            return Array(self[start...end])
        }
    }
    func jc_subarrayToEnd(from start: Int) -> [Element] {
        return jc_subarray(from: start, to: endIndex)
    }
    func jc_subarrayFromStart(to end: Int) -> [Element] {
        return jc_subarray(from: 0, to: end)
    }
    func jc_subarrayFromStart(withLength length: Int) -> [Element] {
        if length < count {
            return jc_subarrayFromStart(to: length - 1)
        } else {
            return self
        }
    }
    func jc_subarrayFromEnd(withLength length: Int) -> [Element] {
        if length < count {
            return jc_subarray(from: endIndex - (length - 1), to: endIndex)
        } else {
            return self
        }
    }
    func jc_subarray(from start: Int, length: Int) -> [Element] {
        return jc_subarray(from: start, to: start + length - 1)
    }
}

func + <T>(lhs: [T], rhs: [T]) -> [T] {
    var result = [T]()
    result.append(contentsOf: lhs)
    result.append(contentsOf: rhs)
    return result
}
func += <T>( lhs: inout [T], rhs: [T]) {
    lhs.append(contentsOf: rhs)
}
